﻿#region

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CuongHanh.Context;
using CuongHanh.DAL;
using CuongHanh.Models;
using CuongHanh.Models.View;
using CuongHanh.Security;
using Ext.Net.MVC;

#endregion

namespace CuongHanh.Controllers.BO
{
    [CustomAuthorize(Key = "Management", Description = "Manage all apps")]
    public class ASubCategoryController : ABaseController
    {
        public ActionResult Index(int branchId)
        {
            ViewBag.branchId = branchId;
            return View();
        }

        public ActionResult ShowAdd(string containerId,
                int branchId)
        {
            return ShowWindow("Add",
                    containerId,
                    new SubCategory(branchId));
        }

        [HttpPost]
        public ActionResult Add(SubCategory model)
        {
            SubCategory newModel = new SubCategory(model);
            UpdateResult result = InsertSubCategory(newModel);
            ShowWindow("wdModify",
                    false);
            ReloadStore("storeGvData");
            ShowNotification(result);
            return this.Direct();
        }

        public ActionResult Command(string containerId,
                string command,
                int id)
        {
            if(command == "Delete")
            {
                UpdateResult result = DeleteSubCategory(id);
                ReloadStore("storeGvData");
                ShowNotification(result);
            }
            if(command == "Edit")
            {
                SubCategory model = GetSubCategory(id);
                return ShowWindow("Edit",
                        containerId,
                        model);
            }
            return this.Direct();
        }

        [HttpPost]
        public ActionResult Edit(SubCategory model)
        {
            UpdateResult result = UpdateSubCategory(model);
            ShowWindow("wdModify",
                    false);
            ReloadStore("storeGvData");
            ShowNotification(result);
            return this.Direct();
        }

        public ActionResult GetDatas(int branchId,
                int start,
                int limit,
                string sort,
                string query)
        {
            return Content(GetSubCategoriesByBranch(branchId,
                    start,
                    limit,
                    sort,
                    query),
                    "json");
        }

        #region SubCategory

        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        public string GetSubCategories(int start,
                int limit,
                string sort,
                string q)
        {
            IQueryable<SubCategory> q1 = _unitOfWork.Where<SubCategory>(c => c.NameVi.Contains(q) && c.NameEn.Contains(q) && c.NameZh.Contains(q) && !c.Inactive);
            IQueryable<Category> q2 = _unitOfWork.Where<Category>(c => !c.Inactive);
            var query = q1.Join(q2,
                    c => c.CategoryId,
                    v => v.Id,
                    (c,
                            v) => new
                                  {
                                          c.Id,
                                          branchId = c.BranchId,
                                          CategoryName = v.NameVi,
                                          CategoryNo = v.No,
                                          c.Code,
                                          c.NameVi,
                                          c.NameEn,
                                          c.NameZh,
                                          c.No,
                                          c.LastModified
                                  });

            return FormatResult(query.Count(),
                    query.OrderBy(c => c.CategoryNo).ThenBy(c => c.No).Skip(start).Take(limit));
        }

        public string GetSubCategoriesByBranch(int branchId,
                int start,
                int limit,
                string sort,
                string q)
        {
            IEnumerable<SubCategory> q1 = CacheContext<SubCategory>.Singleton.GetObjectsByFilter(c => c.BranchId == branchId && (c.NameVi.Contains(q) || c.NameEn.Contains(q) || c.NameZh.Contains(q)) && !c.Inactive);
            IEnumerable<Category> q2 = CacheContext<Category>.Singleton.GetObjectsByFilter(c => c.BranchId == branchId && !c.Inactive);
            var query = q1.Join(q2,
                    c => c.CategoryId,
                    v => v.Id,
                    (c,
                            v) => new
                                  {
                                          c.Id,
                                          branchId = c.BranchId,
                                          CategoryName = v.NameVi,
                                          CategoryNo = v.No,
                                          c.Code,
                                          c.NameVi,
                                          c.NameEn,
                                          c.NameZh,
                                          c.No,
                                          c.LastModified
                                  })
                    .OrderBy(c => c.CategoryNo).ThenBy(c => c.No)
                    .Skip(start).Take(limit).ToList();

            return FormatResult(query.Count,
                    query);
        }

        public SubCategory GetSubCategory(int id)
        {
            return CacheContext<SubCategory>.Singleton.GetObject(id);
        }

        public UpdateResult InsertSubCategory(SubCategory model)
        {
            _unitOfWork.Insert(model);
            _unitOfWork.Save();
            CacheContext<SubCategory>.Singleton.UpdateCached(model);
            Cached.Sigleton.LoadMenuByBranch(model.BranchId);
         
            return new UpdateResult(1,
                    string.Format("Insert SubCategory {0} successful!",
                            model.NameVi));
        }

        public UpdateResult UpdateSubCategory(SubCategory newModel)
        {
            SubCategory model = _unitOfWork.GetById<SubCategory>(newModel.Id);
            if(model != null)
            {
                model.UpdateInfoFrom(newModel);
                _unitOfWork.Save();
                CacheContext<SubCategory>.Singleton.UpdateCached(model);
                Cached.Sigleton.LoadMenuByBranch(model.BranchId);
               
                return new UpdateResult(1,
                        string.Format("Update SubCategory {0} successful!",
                                newModel.NameVi));
            }
            return new UpdateResult(4,
                    string.Format("Update SubCategory {0} error!",
                            newModel.NameVi));
        }

        public UpdateResult DeleteSubCategory(int id)
        {
            SubCategory oldModel = _unitOfWork.GetById<SubCategory>(id);
            if(oldModel != null)
            {
                oldModel.Delete();
                _unitOfWork.Save();
                CacheContext<SubCategory>.Singleton.UpdateCached(oldModel);
                Cached.Sigleton.LoadMenuByBranch(oldModel.BranchId);
               
                return new UpdateResult(1,
                        string.Format("Delete SubCategory {0} successful!",
                                id));
            }
            return new UpdateResult(4,
                    string.Format("Delete SubCategory {0} error!",
                            id));
        }

        public string GetCategoriesComboByBranch(int branchId)
        {
            var query = CacheContext<Category>.Singleton.GetObjectsByFilter(c => c.BranchId == branchId && !c.Inactive)
                    .Select(c => new
                                 {
                                         c.Id,
                                         Name = c.NameVi,
                                 }).OrderBy(c => c.Name).ToList();

            return FormatResult(query.Count,
                    query);
        }

        public string GetSubCategoriesComboByBranch(int branchId)
        {
            var query = CacheContext<SubCategory>.Singleton.GetObjectsByFilter(c => c.BranchId == branchId && !c.Inactive)
                    .Select(c => new
                                 {
                                         c.Id,
                                         Name = c.NameVi,
                                 }).OrderBy(c => c.Name).ToList();

            return FormatResult(query.Count,
                    query);
        }

        #endregion
    }
}
